import React from "react";
import Header from '../../components/Header';
import TodoItem from "./TodoItem";
import './TodoStyle.css';

class TodoList extends React.Component {

    constructor() {
        super();

        this.state = {
            inputVal: '',
            list: []
        };

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleItemClick = this.handleItemClick.bind(this);
    }

    handleInputChange(e) {
        this.setState({
            inputVal: e.target.value
        });
    }

    handleBtnClick() {
        const { list } = this.state;
        list.push(this.state.inputVal);
        this.setState({
            list: list,
            inputVal: ''
        });
    }

    handleItemClick(delIndex) {
        const { list } = this.state;
        list.splice(delIndex, 1);
        this.setState({
            list: list
        });

    }

    render() {
        return (
            <div className="wrap todo-list">
                <Header title='todo列表' />
                <input value={ this.state.inputVal } onChange={ this.handleInputChange } />
                <button className="btn" onClick={ this.handleBtnClick }>添加</button>
                <ul>
                    {
                        this.state.list.map((item, index) => {
                            return (
                                <React.Fragment key={ index }>
                                    <TodoItem index={ index } data={ item } delete={ this.handleItemClick }></TodoItem>
                                    ----------
                                </React.Fragment>
                            );
                        })
                    }
                </ul>
            </div>
        );
    }
}

export default TodoList;